module.exports = app => {
  const express = require('express')
  const router = express.Router()

  registerSimpleRouter()
  registerBaseRouter()
  registerErrorRouter()
  registerExtendRouter()

  registerInterceptorRouter()
  registerConfigRouter()


  app.use(router)
  //全局错误处理
  app.use(function (err, req, res, next) {
    //console.log("错误:"+err.message)
    return res.send({
      state: 'error',
      msg: err.message
    })
  })

  function registerSimpleRouter() {
    router.get('/simple/get', (req, res) => {
      res.send({
        msg: "hello world"
      })
    })
  }

  function registerBaseRouter() {
    router.post('/base/post', function (req, res) {
      res.json(req.body)
    })

    router.post('/base/buffer', function (req, res) {
      let msg = []
      req.on('data', (chunk) => {
        if (chunk) {
          msg.push(chunk)
        }
      })
      req.on('end', () => {
        let buf = Buffer.concat(msg)
        res.json(buf.toJSON())
      })
    })
  }

  function registerErrorRouter() {


    router.get('/error/get', function (req, res) {
      if (Math.random() > 0.5) {
        res.json({
          msg: `hello world`
        })
      } else {
        res.status(500)
        res.end()
      }
    })

    router.get('/error/timeout', function (req, res) {
      setTimeout(() => {
        res.json({
          msg: `hello world`
        })
      }, 3000)
    })
  }

  function registerExtendRouter() {
    router.get('/extend/get', function (req, res) {
      res.json({
        msg: 'hello world'
      })
    })

    router.options('/extend/options', function (req, res) {
      res.end()
    })

    router.delete('/extend/delete', function (req, res) {
      res.end()
    })

    router.head('/extend/head', function (req, res) {
      res.end()
    })

    router.post('/extend/post', function (req, res) {
      res.json(req.body)
    })

    router.put('/extend/put', function (req, res) {
      res.json(req.body)
    })

    router.patch('/extend/patch', function (req, res) {
      res.json(req.body)
    })

    router.get('/extend/user', function (req, res) {
      res.json({
        code: 0,
        message: 'ok',
        result: {
          name: 'jack',
          age: 18
        }
      })
    })
  }

  function registerInterceptorRouter() {
    router.get('/interceptor/get', function (req, res) {
      res.end('hello')
    })
  }

  function registerConfigRouter() {
    router.post('/config/post', function (req, res) {
      res.json(req.body)
    })
  }
}
